'use strict'

const Controller = require('egg').Controller
const jwt = require('jsonwebtoken')

class UsersController extends Controller {
	async index() {
		const { ctx } = this
		ctx.body = 'hi, egg'
	}

	// 登陆
	async login() {
		const { ctx, app } = this
		const { phone, password } = ctx.request.body
		const loginData = await app.mysql.get('users', { phone, password })
		console.log(loginData, 'loginData')
		if (!loginData) {
			ctx.body = { code: 0, msg: '请注册' }
		} else {
			// 生成token，
			const token = jwt.sign({ ...loginData, password: '' }, '1904A', {
				expiresIn: '24h'
			})
			ctx.body = { code: 0, msg: '登陆成功', token }
		}
	}

	// 验证码

	// 注册
	async register() {
		const { ctx, app } = this
		const { phone, email, nickname, avatar = '', password } = ctx.request.body
		const registerData = await app.mysql.insert('users', {
			phone,
			email,
			nickname,
			avatar,
			password
		})
		if (registerData.affectedRows) {
			ctx.body = { code: 0, msg: '注册成功' }
		} else {
			ctx.body = { code: 0, msg: '注册失败' }
		}
	}

	// 查询用户列表
	async findUsers() {
		const { ctx, app } = this
		const { page, size } = ctx.request.body
		const findUsersData = await app.mysql.select('users', {
			limit: size * 1,
			offset: (page - 1) * size,
			columns: ['id', 'nickname', 'email', 'avatar', 'phone'] // 要查询哪个字段
			// orders: [['id', 'desc']] // 倒序排列
			// where: { nickname: 'zhangsan' } // WHERE 条件
		})
		ctx.body = { code: 0, msg: 'success', data: findUsersData }
	}
}

module.exports = UsersController
